// SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
// SPDX-License-Identifier: Mulan PSL v2
package storage

import (
	"fmt"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"

	"code.geniusai.org/notebook-manager/pkg/config"
)

var (
	LogLevelMap = map[string]logger.LogLevel{
		"":       logger.Silent,
		"Info":   logger.Info,
		"Silent": logger.Silent,
	}
)

func NewMysqlDB(c *config.MysqlConf) (*gorm.DB, error) {

	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?%s", c.User, c.Passwd, c.Url, c.Port, c.DbName, c.Args)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger:                                   logger.Default.LogMode(LogLevelMap[c.LogLevel]),
		DisableForeignKeyConstraintWhenMigrating: true,
		PrepareStmt:                              true,
	})
	return db, err
}
